using System.Drawing;
using System.IO;
using GTA;
using NativeUI;

namespace CustomPeds.Menus;

public class PreLoadedMenu : Script
{
    public static UIMenu menu = new UIMenu("", TextSetting.gf_Menu, new Point(0, -107));

    private static bool inited;

    public PreLoadedMenu()
    {
        if (!inited)
        {
            Main.pool.Add(menu);
            menu.OnItemSelect += OnItemSelect;
            menu.OnMenuClose += OnMenuClose;
            inited = true;
        }
    }

    public static void InitPreLoadedMenu()
    {
        menu.Clear();
        menu.SetBannerType(new UIResRectangle());
        FileInfo[] files = new DirectoryInfo($"{Skin.SKIN_PATH}").GetFiles("*.skin", SearchOption.AllDirectories);
        for (int i = 0; i < files.Length; i++)
        {
            string text = Path.GetFileNameWithoutExtension(files[i].FullName);
            if (text == GirlfriendMenu.DefaultSkinGF)
            {
                text = "~y~" + text;
            }
            menu.AddItem(new UIMenuItem(text));
        }
        menu.RefreshIndex();
        menu.Visible = true;
    }

    private void OnItemSelect(UIMenu sender, UIMenuItem item, int index)
    {
        GirlfriendMenu.DefaultSkinGF = menu.MenuItems[index].Text.Replace("~y~", "");
        InitPreLoadedMenu();
    }

    private void OnMenuClose(UIMenu sender)
    {
        // 仅隐藏自身，不刷新；返回时显式恢复上级并避免重叠
        menu.Visible = false;
        try
        {
            if (GirlfriendMenu.menu != null)
            {
                GirlfriendMenu.menu.Visible = true;
                GirlfriendMenu.menu.RefreshIndex();
            }
        }
        catch { }
    }
}


